<template>
  <div>
    <div class="upload-components">
      <el-upload
        v-if="!(limit == imgObj.srcList.length)"
        list-type="picture-card"
        ref="upload"
        multiple
        :limit="limit"
        :accept="accept"
        :show-file-list="false"
        :auto-upload="true"
        :headers="headers"
        :http-request="uploadFileFun"
        :on-exceed="onExceed"
        :before-upload="beforeUpload"
        :on-change="onChange"
        class="upload-comp img-space"
      >
        <template #default>
          <div class="icon-plus">
            <span class="icon-plus-inner">
              <i class="el-icon-plus"></i>
              <span class="icon-plus-txt">上传图片</span>
            </span>
          </div>
        </template>
      </el-upload>
      <!-- 图片预览 -->
      <div class="img-list img-space" v-for="(item, i) in imgObj.srcList" :key="i">
        <el-image class="img-preview" fit="cover" :src="item" :preview-src-list="imgObj.srcList"></el-image>
        <div class="img-setting main-img" v-if="showSetFlag && item == imgObjData.mainImg">商品主图</div>
        <div class="img-setting" v-if="showSetFlag && item != imgObjData.mainImg" @click="setMainImg(item)">设为主图</div>
        <i class="el-icon-error close-icon" @click="handleRemove(i)"></i>
      </div>
    </div>
    <div class="upload-tip">{{ imgUploadTip }}</div>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  nextTick,
  watch,
  ref,
  reactive,
  onMounted
} from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { getSTSToken } from "@/api/service/upload";
import axios from "axios"; // 基于 promise 的 HTTP 库

// import OSS from "ali-oss";
export default defineComponent({
  components: {},
  props: {
    imgUploadTip: {
      type: String,
      default: "只支持. jpg 格式，尺寸为800*800，最多6张"
    },
    limit: {
      type: Number,
      default: 1
    },
    fileType: {
      type: Array,
      default: []
    },
    showSetFlag: {
      type: Boolean,
      default: true
    },
    imgProps: {
      type: Object,
      default: {
        width: "",
        height: ""
      }
    },
    imgObjData: {
      type: Array,
      default: {}
    }
  },
  setup(props, ctx) {
    const fileType = props.fileType.join(",");
    const accept = ref(fileType);
    const headers = reactive({
      // 附件上传需要的token
      Authorization: ""
    });
    const imgObj = reactive({
      url: "",
      srcList: []
    });
    imgObj.srcList = props.imgObjData.srcList;
    // 商品主图设置
    const setMainImg = (url) => {
      ctx.emit("setMainImg", url)
    };
    // 文件超出个数限制时的钩子
    const onExceed = (files, fileList) => {
      console.log(files);
      console.log(fileList);
      if (files.length > props.limit) {
        ElMessage.error(`温馨提示：最多可以上传${props.limit}张图片`);
        return;
      } else {
        let params = { file: null };
        params.file = files[0];
        uploadFileFun(params);
      }
    };
    // 上传之前
    const beforeUpload = file => {
      console.log(file);
    };
    // onChange
    const onChange = (file, fileList) => {
      // console.log(file)
      // console.log(fileList)
    };
    // 删除图片
    const handleRemove = i => {
      imgObj.srcList.splice(i, 1);
    };
    const uploadFileFun = params => {
      console.log(params);
      const _file = params.file || params.row;
      const isLt2M = _file.size / 1024 / 1024 <= 5;
      const fileType = props.fileType || [".JPEG", ".JPG"];
      const type = _file.name.substr(_file.name.lastIndexOf(".")).toUpperCase();
      // 上传类型限制
      if (!fileType.includes(type)) {
        let type = fileType.join(",");
        ElMessage.error(`温馨提示：只支持${type}格式`);
        return;
      }
      if (!isLt2M) {
        ElMessage.error("文件最大不能超过5MB");
        return false;
      }
      // 通过 FormData 对象上传文件
      var formData = new FormData();
      formData.append("file", _file);

      let reader = new FileReader();
      reader.readAsDataURL(_file);
      let blob = null;
      reader.onload = e => {
        console.log(e);
        let img: any = document.createElement("img");
        img.src = e.target.result;
        img.onload = async () => {
          console.log(img.width);
          console.log(img.height);
          if (props.imgProps.width) {
            if (
              img.width != props.imgProps.width ||
              img.height != props.imgProps.height
            ) {
              ElMessage.error(
                `温馨提示：请上传${props.imgProps.width} * ${props.imgProps.height}尺寸的图片`
              );
              return;
            }
          }

          // var loading = ElLoading.service({
          //   lock: true,
          //   text: "上传中...",
          //   spinner: "el-icon-loading",
          //   background: "rgba(0, 0, 0, 0.7)"
          // });

          if (props.limit <= imgObj.srcList.length) {
            // loading.close();
            await ElMessage.error(`温馨提示：最多可以上传${props.limit}张图片`);
            return;
          }
          uploadImg(params);
          // imgObj.srcList.push(e.target.result);
          console.log(imgObj);
          // loading.close();
        };
      };
    };
    let STSTokenData = reactive({});
    // 获取ststoken及相应参数
    const getSTSTokenFun = () => {
      getSTSToken().then(res => {
        if (res.code == 200) {
          STSTokenData = res.data;
          console.log(STSTokenData);
        }
      });
    };
    getSTSTokenFun();
    const uploadImg = file => {
      // 这里是OSS，需要配置oss
      const client = new OSS.Wrapper({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
        region: "oss-cn-shanghai",
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        accessKeyId: STSTokenData.AccessKeyId,
        accessKeySecret: STSTokenData.AccessKeySecret,
        stsToken: STSTokenData.SecurityToken,
        endpoint: "https://" + "oss-accelerate.aliyuncs.com", // 拼上https防止跨域
        // 填写Bucket名称。
        bucket: "whaleyunxun-werich",
        secure: true,
        // cname: true
      });
      console.log(file);
      var f = file.file;
      const Name = f.name;
      const suffix = Name.substr(Name.indexOf("."));
      const obj = "";
      // 图片路径的
      let storeAs = ''
      storeAs = `WhaleMall/${props.imgObjData.path ? props.imgObjData.path : 'web-imgs'}/` + obj + Name; // 路径+时间戳+后缀名
      // 当类型为广告位的时候传入原来的固定地址
      if (props.imgObjData.type === 'absense') {
        storeAs = `WhaleMall/advertisement/${props.imgObjData.picName}`; // 路径+时间戳+后缀名
      }
      // multipartUpload 分片上传
      const progress = (p, _checkpoint) => {
        console.log(p); // Object的上传进度。
        console.log(_checkpoint); // 分片上传的断点信息。
      };
      client
        .multipartUpload(storeAs, f)
        .then(result => {
          console.log("result.res",result.res);
          let aliUrl = result.res.requestUrls;
          console.log(aliUrl[0]); // 阿里云返回给的url
          let domainName = "https://whaleyunxun-werich.oss-accelerate.aliyuncs.com";
          const url = `${domainName}/${storeAs}`;
          imgObj.srcList.push(url);
          console.log(imgObj.srcList);
        })
        .catch(function(err) {
          console.log(err);
        });
    };
    const randomString = (len = 32) => {
      len = len || 32;
      let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let maxPos = chars.length;
      let pwd = "";
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    };
    return {
      imgObj,
      handleRemove,
      uploadFileFun,
      accept,
      onExceed,
      beforeUpload,
      onChange,
      getSTSTokenFun,
      STSTokenData,
      uploadImg,
      randomString,
      setMainImg
    };
  }
});
</script>

<style lang="scss" scoped>
.upload-components {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  .img-space {
    margin: 0 10px 10px 0;
  }
}
.icon-plus {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 146px;
  height: 146px;
  .icon-plus-inner {
    height: 50px;
    line-height: 20px;
  }
  .icon-plus-txt {
    height: 20px;
    display: block;
    line-height: 20px;
  }
}
.img-preview {
  width: 148px;
  height: 148px;
  border-radius: 5px;
  border: 1px solid #eee;
  box-shadow: 0 0 5px #eee;
  // background: #fbfdff;
  background: #ffffff;
}
.img-list {
  position: relative;
  width: 148px;
  height: 148px;
  .close-icon {
    position: absolute;
    top: -10px;
    right: -10px;
    color: #ff7878;
    font-size: 20px;
    background: #ffffff;
    border-radius: 50%;
    cursor: pointer;
    &:hover {
      opacity: 0.9;
    }
  }
  .img-setting {
    position: absolute;
    bottom: -1px;
    left: 0;
    color: #ffffff;
    text-align: center;
    width: 100%;
    box-sizing: border-box;
    cursor: pointer;
    background: rgba(0, 0, 0, 0.3);
    height: 30px;
  }
  .main-img{
    color: #02f2ff;
  }
}
.upload-tip {
  color: #a2a2a2;
}
</style>
